<template>
  <div class="page-wapper">
    <!-- 版本管理 -->
    <div class="container">
      <!-- 顶部搜索栏 -->
      <div class="search_bar">
        <div class="left_search">
          <div class="filter_item">
            <div class="label">版本名称：</div>
            <el-input
              v-model="filterData.releaseName"
              size="small"
              placeholder="请输入"
              clearable
              @keyup.enter="handleSearch"
            ></el-input>
          </div>
        </div>
        <div class="right_search">
          <el-button-group>
            <el-button
              size="mini"
              :loading="searchBtnLoading"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button size="mini" @click="handleReset"> 重置 </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="table_options_bar">
        <div></div>
        <div>
          <el-button size="mini" type="primary" @click="createTableData">
            新建
          </el-button>
          <el-button size="mini" type="danger" @click="batchdelete">
            删除
          </el-button>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          :sort-config="{ remote: true }"
          :menu-config="{}"
          :checkbox-config="{ checkField: 'checked', trigger: 'row' }"
          :row-style="rowStyle"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          show-overflow="tooltip"
          highlight-hover-row
          highlight-current-row
          class="xTable"
        >
          <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>

          <vxe-column
            type="seq"
            title="序号"
            width="60"
            fixed="left"
          ></vxe-column>

          <vxe-column
            field="releaseName"
            title="版本名称"
            min-width="200"
            align="left"
            header-align="center"
          >
          </vxe-column>

          <vxe-column
            field="releaseDesc"
            title="版本描述"
            min-width="200"
            align="left"
            header-align="center"
          ></vxe-column>

          <vxe-column
            field="releaseSort"
            title="版本排序"
            width="80"
            align="center"
            header-align="center"
          ></vxe-column>

          <vxe-column
            #default="{ row }"
            width="100"
            title="设为标签"
            fixed="right"
          >
            <div style="text-align: center">
              <el-switch
                v-model="row.asRoof"
                :loading="row.roofLoading"
                @change="changeRoof(row)"
                @click.stop=""
              />
            </div>
          </vxe-column>

          <vxe-column #default="{ row }" width="160" title="操作" fixed="right">
            <div>
              <el-button
                size="mini"
                type="text"
                @click.stop="editTableDataMethod(row)"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click.stop="deleteTableDataMethod(row)"
              >
                删除
              </el-button>
            </div>
          </vxe-column>
        </vxe-table>
      </div>
      <el-pagination
        v-model="pagenationData.current"
        :page-sizes="[500, 100, 50, 15]"
        :page-size="pagenationData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagenationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        style="text-align: center; margin-top: 10px"
      >
      </el-pagination>
    </div>

    <!-- 编辑弹框 -->
    <ReleaseFormDialog ref="releaseFormDialogRef" @refresh="getTableData" />
  </div>
</template>

<script>
import { ref, reactive, nextTick, getCurrentInstance } from "vue";
import ReleaseFormDialog from "./components/ReleaseFormDialog.vue";
import { ElMessage, ElMessageBox } from "element-plus";

const initFilterData = () => {
  return {
    releaseName: null,
  };
};

export default {
  name: "ReleaseManage",
  components: { ReleaseFormDialog },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;

    const releaseFormDialogRef = ref(null);

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});

    const xTable = ref(null);
    const tableData = ref([]);
    const tableLoading = ref(false);
    const searchBtnLoading = ref(false);
    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    const isFullScreen = ref(false);
    const toggleFullScreen = () => {
      isFullScreen.value = !isFullScreen.value;
    };

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      tableLoading.value = true;
      $api.release
        .listPage({
          ...pagenationData,
          condition,
        })
        .then((res) => {
          tableLoading.value = false;
          console.log("tableData => res", res);
          tableData.value = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
              roofLoading: false,
            };
          });
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableLoading.value = false;
          console.error("tableData error: ", err);
        });
    };

    // 新建
    const createTableData = () => {
      nextTick(() => {
        releaseFormDialogRef.value.open();
      });
    };

    // 编辑内容
    const editTableDataMethod = (row) => {
      nextTick(() => {
        releaseFormDialogRef.value.open(row);
      });
    };

    // 删除单个内容
    const deleteTableDataMethod = (row) => {
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除【${
          row.releaseName.length > 10
            ? row.releaseName.slice(0, 10) + "..."
            : row.releaseName
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          deleteTableData([row.id]);
        })
        .catch(() => {});
    };

    // 删除内容接口
    const deleteTableData = (ids) => {
      tableLoading.value = true;
      $api.release
        .removeByIds({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 动态设置单元行样式
    const rowStyle = ({ rowIndex }) => {
      if (tableData.value[rowIndex].checked) {
        return {
          backgroundColor: "pink",
          // backgroundColor: 'lightblue',
          // color: '#ffffff'
        };
      }
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    // 设为标签置顶
    const changeRoof = (row) => {
      row.roofLoading = true;
      $api.release
        .toggleRoof({
          id: row.id,
          asRoof: row.asRoof,
        })
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .catch((err) => {
          console.error("toggleRoof error: ", err);
        })
        .finally(() => {
          row.roofLoading = false;
          getTableData();
        });
    };

    // 批量删除
    const batchdelete = () => {
      if (!tableData.value.length) {
        return ElMessage.warning("没啥可删的");
      }
      const selectedList = tableData.value.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除 ${selectedList.length} 条数据吗？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          const ids = selectedList.map((item) => item.id);
          deleteTableData(ids);
        })
        .catch(() => {});
    };

    // 初始化
    handleSearch();

    return {
      xTable,
      tableData,
      tableLoading,
      rowStyle,
      isFullScreen,
      toggleFullScreen,
      searchBtnLoading,
      handleSearch,
      handleReset,
      filterData,
      createTableData,
      getTableData,
      releaseFormDialogRef,
      pagenationData,
      handleSizeChange,
      handleCurrentChange,
      editTableDataMethod,
      deleteTableDataMethod,
      changeRoof,
      batchdelete,
    };
  },
};
</script>

<style>
.message-title {
  cursor: pointer;
}
.handle-row {
  margin-top: 30px;
}
</style>
